// src/hooks/useChatStream.ts
import { fetchEventSource } from "@microsoft/fetch-event-source";
import { ref } from "vue";

const API_BASE_URL = "http://localhost:3000/api";
const MAX_RETRIES = 3;
const BASE_DELAY = 1000;

export const useChatStream = () => {
  const controller = new AbortController();
  const isStreaming = ref(false);
  const error = ref(null);
  let lastEventId = "";
  let retries = 0;
  // 消息索引
  let currentIndex = 0;
  // 所有的消息
  let allMessage = "";
  // 一次加载多少个字符
  let stringNumber = 1;
  // 多久加载一次
  let timeNumber = 100;
  // 定时器
  let timer = null;

  /** 中断请求 */
  const abort = () => {
    controller.abort();
    isStreaming.value = false;

    // 发送中止请求到服务端
    fetch(`${API_BASE_URL}/chat/stop`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    }).catch(err => {
      console.error('中止请求失败:', err);
    });

    // 清理定时器和状态
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }
    currentIndex = 0;
    allMessage = '';
  };

  /** 流式对话处理 */
  const streamChat = async (messages, input) => {
    console.log('????')
    // 重置状态
    error.value = null;
    retries = 0;

    // 添加用户消息
    const userMessage = {
      id: `user_${Date.now()}`,
      role: "user",
      content: input,
      timestamp: Date.now(),
    };
    messages.value = [...messages.value, userMessage];

    // 初始化AI消息
    const assistantMessage = {
      id: `temp_${Date.now()}`,
      role: "assistant",
      content: "",
      timestamp: Date.now(),
    };
    messages.value = [...messages.value, assistantMessage];

    isStreaming.value = true;

    try {
      await fetchEventSource(API_BASE_URL + "/chat", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${localStorage.getItem("token")}`,
          "Last-Event-ID": lastEventId,
        },
        body: JSON.stringify({ message: input }),
        signal: controller.signal,

        // 连接建立处理
        async onopen(response) {
          if (!response.ok) {
            throw new Error(`HTTP ${response.status} - ${response.statusText}`);
          }
        },

        // 消息处理
        onmessage(ev) {
          try {
            if (ev.id) lastEventId = ev.id;
            if (ev.data === "done") {
              isStreaming.value = false;
              return;
            }
            if (!ev.data) return;
            //最新的消息
            const chunk = ev.data;
            //所有的消息
            allMessage = allMessage.concat(chunk);
            // 清除之前的定时器
            if (timer) return;

            // 更新消息内容
            const lastMsg = messages.value[messages.value.length - 1];

            // 流式展示文本的函数
            const showText = () => {
              if (!isStreaming.value) {
                clearTimeout(timer);
                timer = null;
                currentIndex = 0;
                allMessage = '';
                return
              };

              // 如果当前索引小于总消息长度
              if (currentIndex < allMessage.length) {
                // 计算本次要显示的文本
                const endIndex = Math.min(
                  currentIndex + stringNumber,
                  allMessage.length
                );
                const textToShow = allMessage.substring(currentIndex, endIndex);

                // 更新消息内容
                lastMsg.content += textToShow;

                // 更新当前索引
                currentIndex = endIndex;

                // 设置下一次显示的定时器
                timer = setTimeout(showText, timeNumber);
              }
            };

            // 开始流式显示
            showText();
          } catch (e) {
            console.error("消息解析失败:", e);
          }
        },

        // 错误处理（带指数退避重试）
        onerror(err) {
          if (retries < MAX_RETRIES && !controller.signal.aborted) {
            const delay = BASE_DELAY * Math.pow(2, retries);
            retries++;
            setTimeout(() => streamChat(messages, input), delay);
          } else {
            error.value = new Error(`请求失败: ${err.message}`);
            isStreaming.value = false;
          }
        },

        // 连接关闭
        onclose() {
          console.log('关闭了')
          if (!controller.signal.aborted) {
            const lastMsg = messages.value[messages.value.length - 1];
            lastMsg.id = `msg_${Date.now()}`;
            isStreaming.value = false;
          }
        },
      });
    } catch (err) {
      error.value = err;
      isStreaming.value = false;
    }
  };

  return { streamChat, isStreaming, error, abort };
};
